const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const fs = require('fs');
const router = express.Router();
// const app = express();  // 创建一个 Express 实例
const tencentcloud = require("tencentcloud-sdk-nodejs-sms");
// const rateLimit = require('express-rate-limit');



// 存储验证码的对象
const verificationCodes = {};




/* GET home page. */
router.get('/123', function(req, res, next) {
  res.render('index', { title: '访问sms成功' });
});


// 发送验证码
router.post('/yanzheng', async (req, res) => {
  try {
    // 从请求中获取手机号码
    const { phoneNumber } = req.body;
    var temp = Math.random() * 9000; //[0，9000) 
    // 获取1000~9000
    temp = 1000 + parseInt(temp);
    const SmsClient = tencentcloud.sms.v20210111.Client;
    const clientConfig = {
      credential: {
        // 密钥id
        secretId: "AKID176OUN1QcaJn35sQmuVs0tZ0C9sLaaLM", 
        // 密钥密码
        secretKey: "sZ3MUP9h3CAwUpxueIjx1tY0IMDuPioh",
      },
      region: "ap-beijing",
      profile: {
        httpProfile: {
          endpoint: "sms.tencentcloudapi.com",
        },
      },
    };
    const client = new SmsClient(clientConfig);
    const params = {
      "PhoneNumberSet": ["+86" + phoneNumber],
      "SmsSdkAppId": "1400861773",
      "SignName": "小书阁",
      "TemplateId": "2022305",
      "TemplateParamSet": [temp.toString()]
    };
    client.SendSms(params).then(
      (data) => {
        // 存储验证码和过期时间
        verificationCodes[phoneNumber] = {
          code: temp.toString(),
          expiry: Date.now() + 60 * 1000,
        };
        res.send({ code: 200, msg: "验证码发送成功", yanZhengMa: temp.toString(), data });
      },
      (err) => {
        console.error("error", err);
        0
        res.status(500).json({ message: '内部服务器错误' });
      }
    );
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '内部服务器错误' });
  }
});

// 验证验证码
router.post('/verifyCode', async (req, res) => {
  try {
    const { phoneNumber, verificationCode } = req.body;

    // 获取存储的验证码和过期时间
    const storedCode = verificationCodes[phoneNumber];

    if (!storedCode || Date.now() > storedCode.expiry) {
      return res.send({ code: 400, msg: '验证码已过期或不存在' });
    }

    if (verificationCode !== storedCode.code) {
      return res.send({ code: 400, msg: '验证码错误' });
    }

    // 验证通过，清除存储的验证码
    delete verificationCodes[phoneNumber];

    res.send({ code: 200, msg: '验证码验证成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '内部服务器错误' });
  }
});



module.exports = router;